import configData from "../../data/index";
import api from "./api";
import reasetTileset from "./reasetTileset";
import WaterPrimitiveCollection from "./WaterPrimitiveCollection";
import WFSParse from "./WFSParse";
import imageDataApi from "@/views/js/api/imageDataApi";
let customShader = agcim.renderer.b3dmCustomShader;

class IndexFn {
  constructor(viewer) {
    this.viewer = viewer;
    this._dayType = 1;
    this.listener;
    this.waterRender = undefined;
    this.tree = undefined;
    this.yellowFlower = undefined;
    this.purpleFlower = undefined;
    this.grass = undefined;
    this.light = undefined;
    this.bulidingEffectList = []; //存储建筑光效方案数据
    this.bulidingAssociatedList = []; //存储建筑光效关联关系
    this.buildingTextureList = []; //存储贴图列表数据
    this.waterPrimitiveCollection = new WaterPrimitiveCollection();
  }
  async init() {
    this.addBuildingEffect();
     await this.addTreeEffect();
    await this.addRoadLightEffect();
    // await this.addYellowFlowerEffect();
    // await this.addPurpleFlowerEffect();
    // await this.addGrassEffect();
    setTimeout(() => {
      this.addWaterEffect();
    }, 3000);
    let addBuildingTexture = await this.addBuildingTexture();
    setTimeout(() => {
      this.listener = this.viewer.scene.postUpdate.addEventListener(() => {
        let modelType = this.viewer.clock.modelType;
        if (modelType != this._dayType) {
          addBuildingTexture(modelType);
          this.addBuildingEffect();
          this._dayType = modelType;
        }
      });
    }, 1000);
  }
  //建筑光效
  async addBuildingEffect() {
    if (this.bulidingEffectList.length === 0) {
      let bulidingEffectCode = await api.getDirId(
        configData.bulidingEffectCode
      );
      this.bulidingEffectList = await api.getDesignList(
        configData.bulidingEffectList,
        bulidingEffectCode
      );
    }
    if (this.bulidingAssociatedList.length === 0) {
      let bulidingAssociatedCode = await api.getDirId(
        configData.bulidingAssociatedCode
      );
      this.bulidingAssociatedList = await api.getDesignList(
        configData.bulidingAssociatedList,
        bulidingAssociatedCode
      );
    }
    this.bulidingAssociatedList.forEach((item) => {
      let tileUrl = item.imageStoreInformation.url;
      let designId = item.imageStoreInformation.designId;
      let design = this.bulidingEffectList.find(
        (i) => i.imageStoreId == designId
      );
      if (!design) return;
      let primitives = CIM.viewer.scene.primitives._primitives;
      let indexObj = primitives.find((item) => item._url == tileUrl);
      if (indexObj) {
        //销毁掉原先的设计方案
        if (indexObj.customShader && indexObj.customShader.design) {
          //indexObj.customShader.design.destroyed();
          return;
        }
        if (!indexObj.enableModelExperimental) {
          indexObj = reasetTileset.reset(indexObj);
        }
        indexObj.readyPromise.then(() => {
          let instance = new customShader[design.imageStoreInformation.type](
            CIM.viewer,
            design.imageStoreInformation,
            indexObj
          );
          //测试变量
          indexObj.customShader = instance.customShader;
        });
      }
    });
  }

  //动态更换建筑贴图
  async addBuildingTexture() {
    if (this.buildingTextureList.length === 0) {
      let buildingTextureCode = await api.getDirId(
        configData.buildingTextureCode
      );
      this.buildingTextureList = await api.getDesignList(
        configData.buildingTextureList,
        buildingTextureCode
      );
    }

    function apply(tilesetUrl, textureLsit) {
      let tileset = reasetTileset.findTileset(tilesetUrl);
      if (!tileset) return;
      tileset.readyPromise.then((tileset) => {
        let replaceTextrue = new agcim.renderer.ReplaceTextrue(tileset);
        //更换纹理
        for (let i = 0; i < textureLsit.length; i++) {
          replaceTextrue.changeTextrue(textureLsit[i].id, textureLsit[i].image);
        }
      });
    }
    return (modelType) => {
      let newDesignList = this.buildingTextureList.filter((item) => {
        return item.imageStoreInformation.dayType == modelType;
      });
      if (modelType == 1) {
        let tilesetObj = {};
        this.buildingTextureList.map((item) => {
          if (!tilesetObj[item.imageStoreInformation.url]) {
            tilesetObj[item.imageStoreInformation.url] =
              reasetTileset.findTileset(item.imageStoreInformation.url);
          }
        });
        let values = Object.values(tilesetObj);
        values.map((item) => {
          if (item) reasetTileset.reset(item);
        });
      } else {
        newDesignList.map((item) => {
          apply(
            item.imageStoreInformation.url,
            item.imageStoreInformation.textureList
          );
        });
      }
    };
  }

  async getDefaultWaterEffect(){
      let param = {
        dirCode: "other-AgCIM-RiverDesign",
        page: 1,
        rows: 1000,
      };
      return new Promise((resolve) => {
        imageDataApi.selectAuthPageByDirCode(param).then((data) => {
          let riverConfigList = data.content.list.map((item) => {
            item.imageStoreInformation = JSON.parse(item.imageStoreInformation);
            return item;
          });
          resolve(riverConfigList);
        });
      });
  }

  //水体效果
  async addWaterEffect() {
    let waterList = await this.getDefaultWaterEffect();
    // console.log("waterList",waterList);
    let options =  waterList[0].imageStoreInformation.options;
    let height = options.height;
    let feature = await api.getWaterPolygonFromWFS(
      options.wfsUrl,
      options.tableName
    );
    WFSParse.loadFeatureCollectionJsonAndParseAsPolygon(
      feature,
      height
    ).then((dataArray) => {
      if (dataArray instanceof Array && dataArray.length > 0) {
        dataArray.forEach((data) => {
          const waterRender = new agcim.renderer.WaterRender(
            this.viewer,
            options
          );
          waterRender.init(data.positions, data.holes);
          this.waterPrimitiveCollection.addPrimitive(waterRender);
        });
      } else {
        console.info("解析不到wfs返回的数据！");
      }
    });
  }
  //添加树
  async addTreeEffect() {
    let pointsArray = await api.getModelPointsFromWFS(
      configData.treeConfig.layerUrl,
      configData.treeConfig.tableName
    );
    this.tree = new agcim.renderer.BaseModel(
      this.viewer,
      configData.treeConfig
    );
    this.tree.addModelPoint(pointsArray);
  }
  //添加黄花
  async addYellowFlowerEffect() {
    let pointsArray = await api.getModelPointsFromWFS(
      configData.yellowFloweConfig.layerUrl,
      configData.yellowFloweConfig.tableName
    );
    this.yellowFlower = new agcim.renderer.BaseModel(
      this.viewer,
      configData.yellowFloweConfig
    );
    this.yellowFlower.addModelPoint(configData.degressArray);
  }
  //添加紫花
  async addPurpleFlowerEffect() {
    let pointsArray = await api.getModelPointsFromWFS(
      configData.purpleflowerConfig.layerUrl,
      configData.purpleflowerConfig.tableName
    );
    this.purpleFlower = new agcim.renderer.BaseModel(
      this.viewer,
      configData.purpleflowerConfig
    );
    this.purpleFlower.addModelPoint(configData.degressArray);
  }
  //添加草
  async addGrassEffect() {
    let pointsArray = await api.getModelPointsFromWFS(
      configData.grassConfig.layerUrl,
      configData.grassConfig.tableName
    );
    this.grass = new agcim.renderer.BaseModel(
      this.viewer,
      configData.grassConfig
    );
    this.grass.addModelPoint(configData.degressArray);
  }
  //添加路灯
  async addRoadLightEffect() {
    let pointsArray = await api.getModelPointsFromWFS(
      configData.lightConfig.layerUrl,
      configData.lightConfig.tableName
    );
    this.light = new agcim.renderer.Light(this.viewer, configData.lightConfig);
    this.light.addLightPoint(pointsArray);
  }

  destroyed() {
    if (this.listener) this.listener();
    reasetTileset.resetEffect();
    if (this.waterRender) {
      this.waterRender.destroy();
      this.waterRender = undefined;
    }
    if (this.tree) {
      this.tree.destory();
      this.tree = undefined;
    }
    if (this.light) {
      this.light.destory();
      this.light = undefined;
    }
    if (this.yellowFlower) {
      this.yellowFlower.destory();
      this.yellowFlower = undefined;
    }
    if (this.purpleFlower) {
      this.purpleFlower.destory();
      this.purpleFlower = undefined;
    }
    if (this.grass) {
      this.grass.destory();
      this.grass = undefined;
    }
    this.waterPrimitiveCollection.destroy();
    //IndexFn.destroyedFlattenTerrain();
  }
}
//地形压平
IndexFn.flattenTerrain = (extent, flattenHeight) => {
  let rectFlattenTerrain = new agcim.renderer.terrainFlatten.RectFlattenTerrain(
    CIM.viewer
  );
  rectFlattenTerrain.add(
    Cesium.Rectangle.fromDegrees(extent[0], extent[1], extent[2], extent[3]),
    flattenHeight
  );
};
IndexFn.destroyedFlattenTerrain = () => {
  agcim.renderer.terrainFlatten.RectFlattenTerrain.destroyed(CIM.viewer);
};
export default IndexFn;
